﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Joy.Erp.BasicArchives.ItemMasters;
using Joy.Erp.Ufida.Core;
using Microsoft.Extensions.Logging;

namespace Joy.Erp.Ufida.ItemMasters
{
    public class ItemCategorySyncAppService : UfidaAppService, IItemCategorySyncAppService
    {
        protected IItemCategoryRepository ItemCategoryRepository => LazyServiceProvider.LazyGetRequiredService<IItemCategoryRepository>();
        protected IItemCategoryAppService ItemCategoryAppService => LazyServiceProvider.LazyGetRequiredService<IItemCategoryAppService>();
        protected IItemCategoryUfidaAppService ItemCategoryUfidaAppService => LazyServiceProvider.LazyGetRequiredService<IItemCategoryUfidaAppService>();
        protected ItemCategoryManager ItemCategoryManager => LazyServiceProvider.LazyGetRequiredService<ItemCategoryManager>();

        public async Task<AnalysisDto> Analyze‌Async()
        {
            var analysisDto = new AnalysisDto();
            analysisDto.Id = typeof(ItemCategory).FullName;

            // 获取U9数据的ID列表
            var u9list = await ItemCategoryUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID.ToString()).ToHashSet();
            analysisDto.U9Count = u9Ids.Count;

            // 使用数据库查询优化，只查询需要的字段
            var pmcQuery = await ItemCategoryRepository.GetQueryableAsync();

            // 获取PMC总数
            analysisDto.Count = await AsyncExecuter.CountAsync(pmcQuery.Where(x => !x.IsDeleted));

            // 获取已同步的SourceKey列表
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 快速计算已同步数量
            analysisDto.AsyncCount = syncedSourceKeys.Count(key => u9Ids.Contains(key));
            analysisDto.UnasyncCount = analysisDto.U9Count - analysisDto.AsyncCount;
            analysisDto.SelfCount = analysisDto.Count - analysisDto.AsyncCount;

            return analysisDto;
        }

        public async Task<List<long>> GetSyncedIds()
        {
            // 使用数据库查询，只查询已同步的SourceKey
            var pmcQuery = await ItemCategoryRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            return syncedSourceKeys
                .Select(
                    key => long.TryParse(key, out var parsedId) ? (long?)parsedId : null
                )
                .Where(id => id.HasValue)
                .Select(id => id.Value)
                .ToList();
        }

        public async Task<int> CreateByIdsAsync(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            // 批量预查询已存在的记录，避免循环查询数据库
            var pmcQuery = await ItemCategoryRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x =>
                        idStrings.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                    )
                    .Select(x => x.SourceKey)
            );
            var existingSet = new HashSet<string>(existingSourceKeys);

            // 过滤出需要创建的ID
            var needCreateIds = ids.Where(id => !existingSet.Contains(id.ToString())).ToList();
            if (needCreateIds.Count == 0)
                return ids.Length;

            Logger.LogInformation($"[批量同步-物料分类] 开始处理 {needCreateIds.Count} 条新增，已存在 {existingSet.Count} 条");

            // 为了确保父级先于子级创建，需要先获取U9数据并按Code长度排序
            var u9DataList = new List<(long id, ItemCategoryUfidaDto dto)>();
            foreach (var id in needCreateIds)
            {
                try
                {
                    var itemCategoryUfidaDto = await ItemCategoryUfidaAppService.GetAsync(id);
                    if (itemCategoryUfidaDto != null)
                    {
                        u9DataList.Add((id, itemCategoryUfidaDto));
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料分类] 获取U9数据失败，Id: {id}");
                }
            }

            if (u9DataList.Count == 0) return existingSet.Count;

            // 按Code长度排序，确保父级先于子级创建
            var sortedList = u9DataList.OrderBy(x => x.dto.Code?.Length ?? int.MaxValue).ToList();

            var successCount = 0;
            using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
            {
                try
                {
                    foreach (var (id, dto) in sortedList)
                    {
                        try
                        {
                            var result = await CreateByIdAsync(id);
                            if (result)
                            {
                                successCount++;
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogWarning(ex, $"[批量同步-物料分类] 创建实体失败，Id: {id}");
                        }
                    }

                    await uow.CompleteAsync();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料分类] 批量创建失败，{ex.Message}");
                }
            }

            Logger.LogInformation($"[批量同步-物料分类] 完成！成功新增 {successCount} 条，总计 {successCount + existingSet.Count} 条");

            return successCount + existingSet.Count;
        }

        public async Task<int> UpdateByIds‌Async(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            Logger.LogInformation($"[批量同步-物料分类] 开始处理 {ids.Length} 条物料分类更新");

            var pmcQuery = await ItemCategoryRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingEntities = await AsyncExecuter.ToListAsync(
                pmcQuery.Where(x =>
                    idStrings.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );

            if (existingEntities.Count == 0)
            {
                Logger.LogWarning($"[批量同步-物料分类] 没有找到需要更新的记录");
                return 0;
            }

            var entityDict = existingEntities.ToDictionary(x => x.SourceKey, x => x);

            var allU9DataDict = new Dictionary<long, ItemCategoryUfidaDto>();
            foreach (var id in ids)
            {
                try
                {
                    var itemCategoryUfidaDto = await ItemCategoryUfidaAppService.GetAsync(id);
                    if (itemCategoryUfidaDto != null)
                    {
                        allU9DataDict[id] = itemCategoryUfidaDto;
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料分类] 获取U9数据失败，Id: {id}");
                }
            }

            var parentCodeToIdMap = new Dictionary<string, long>();
            foreach (var dto in allU9DataDict.Values)
            {
                var u9ParentCodeLength = dto.Code.GetParentCodeLength(dto.TreeRule);
                if (u9ParentCodeLength > 0)
                {
                    var u9ParentCode = dto.Code.Substring(0, u9ParentCodeLength);
                    if (!parentCodeToIdMap.ContainsKey(u9ParentCode))
                    {
                        var parentItemCategory = await ItemCategoryUfidaAppService.FindByCodeAsync(
                            u9ParentCode
                        );
                        if (parentItemCategory != null)
                        {
                            parentCodeToIdMap[u9ParentCode] = parentItemCategory.ID;
                        }
                    }
                }
            }

            var allParentIds = parentCodeToIdMap.Values.Distinct().ToList();
            var parentCategoryCacheDict = await BatchLoadItemCategories(allParentIds.Select(x => x.ToString()).ToList());

            var entitiesToUpdate = new List<ItemCategory>();
            var entitiesToDelete = new List<ItemCategory>();

            foreach (var id in ids)
            {
                try
                {
                    var key = id.ToString();
                    if (!entityDict.TryGetValue(key, out var entity)) continue;

                    if (!allU9DataDict.TryGetValue(id, out var u9Data))
                    {
                        entitiesToDelete.Add(entity);
                        continue;
                    }

                    entity.DisplayName = u9Data.Name;
                    entity.ParentId = null;
                    entity.SourceCreatedOn = u9Data.CreatedOn;

                    var u9ParentCodeLength = u9Data.Code.GetParentCodeLength(u9Data.TreeRule);
                    if (u9ParentCodeLength > 0)
                    {
                        var u9ParentCode = u9Data.Code.Substring(0, u9ParentCodeLength);
                        if (parentCodeToIdMap.TryGetValue(u9ParentCode, out var parentU9Id))
                        {
                            if (parentCategoryCacheDict.TryGetValue(parentU9Id.ToString(), out var parentItemCategoryDto))
                            {
                                entity.ParentId = parentItemCategoryDto.Id;
                            }
                            else
                            {
                                Logger.LogWarning($"[批量同步-物料分类] 未找到父级物料分类，SourceKey: {parentU9Id}");
                            }
                        }
                    }

                    entitiesToUpdate.Add(entity);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料分类] 修改实体失败，Id: {id}");
                }
            }

            var updateCount = 0;
            var deleteCount = 0;
            using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
            {
                try
                {
                    if (entitiesToUpdate.Count > 0)
                    {
                        await ItemCategoryRepository.BulkUpdateAsync(
                            entitiesToUpdate,
                            autoSave: false
                        );
                        updateCount = entitiesToUpdate.Count;
                    }

                    if (entitiesToDelete.Count > 0)
                    {
                        await ItemCategoryRepository.BulkDeleteAsync(
                            entitiesToDelete,
                            autoSave: false
                        );
                        deleteCount = entitiesToDelete.Count;
                    }

                    await uow.CompleteAsync();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料分类] 批量更新/删除失败，{ex.Message}");
                }
            }

            Logger.LogInformation(
                $"[批量同步-物料分类] 完成！成功更新 {updateCount} 条，删除 {deleteCount} 条"
            );

            return updateCount + deleteCount;
        }


        public async Task<List<long>> GetUnasyncIds()
        {
            // 获取U9的所有ID
            var u9list = await ItemCategoryUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID).ToList();

            // 使用数据库查询，只查询已同步的SourceKey
            var pmcQuery = await ItemCategoryRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 优化查找性能，时间复杂度从 O(n²) 降到 O(n)
            var syncedSourceKeySet = new HashSet<string>(syncedSourceKeys);

            // 找出未同步的ID
            var unasyncIds = u9Ids
                .Where(id => !syncedSourceKeySet.Contains(id.ToString()))
                .ToList();

            return unasyncIds;
        }

        private async Task<Dictionary<string, ItemCategoryDto>> BatchLoadItemCategories(
            List<string> sourceKeys
        )
        {
            if (sourceKeys == null || sourceKeys.Count == 0)
                return new Dictionary<string, ItemCategoryDto>();

            var query = await ItemCategoryRepository.GetQueryableAsync();
            var items = await AsyncExecuter.ToListAsync(
                query.Where(x =>
                    sourceKeys.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );

            return items.ToDictionary(
                x => x.SourceKey,
                x => ObjectMapper.Map<ItemCategory, ItemCategoryDto>(x)
            );
        }

        private async Task<bool> CreateById‌Async(long id)
        {
            var existItemCategory = await ItemCategoryAppService.FindBySourceKeyAsync(id.ToString(), SourceConfig.SourceType);
            if (existItemCategory != null) return true;

            var itemCategoryUfidaDto = await ItemCategoryUfidaAppService.GetAsync(id);
            if (itemCategoryUfidaDto == null) return false;

            try
            {
                await CreateAsync(itemCategoryUfidaDto);
                return true;
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, $"CreateById‌Async 创建失败，Id: {id}, 错误信息：{ex.Message}");
                return false;
            }
        }

        private async Task<ItemCategoryDto> CreateAsync(ItemCategoryUfidaDto itemCategoryUfidaDto)
        {
            var itemCategoryCreateDto = new ItemCategoryCreateDto();
            itemCategoryCreateDto.SourceType = SourceConfig.SourceType;
            itemCategoryCreateDto.SourceKey = itemCategoryUfidaDto.ID.ToString();
            itemCategoryCreateDto.DisplayName = itemCategoryUfidaDto.Name;
            itemCategoryCreateDto.SourceCreatedOn = itemCategoryUfidaDto.CreatedOn;
            itemCategoryCreateDto.ParentId = null;

            var u9ParentCodeLength = itemCategoryUfidaDto.Code.GetParentCodeLength(
                itemCategoryUfidaDto.TreeRule
            );
            if (u9ParentCodeLength > 0)
            {
                var u9ParentCode = itemCategoryUfidaDto.Code.Substring(0, u9ParentCodeLength);
                var u9ParentItemCategory = await ItemCategoryUfidaAppService.FindByCodeAsync(
                    u9ParentCode
                );

                if (u9ParentItemCategory != null)
                {
                    var parentItemCategory = await ItemCategoryAppService.FindBySourceKeyAsync(
                        u9ParentItemCategory.ID.ToString(),
                        SourceConfig.SourceType
                    );
                    if (parentItemCategory == null)
                    {
                        parentItemCategory = await CreateAsync(u9ParentItemCategory);
                    }
                    itemCategoryCreateDto.ParentId = parentItemCategory.Id;
                }
            }

            return await ItemCategoryAppService.CreateAsync(itemCategoryCreateDto);
        }
    }
}